package cn.openea.perpartner.componet.config;

import cn.openea.perpartner.componet.util.SendMsgApi;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpInRedisConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;

/**
 * @Name: 自定义发送程序所需要的Bean加载：主要是初始化 WxMpService 和 SendMsgApi 两个实例到窗口
 * @desc: 这里主要是使用了SpringBoot的容器来进行管理
 * @author: Mr.Yun
 * @Created: 2023/02/14 17:41
 */
@Configuration
public class SenderConfig {

    @Value("${tencent.wxmp.appId}")
    private String appId;
    @Value("${tencent.wxmp.secret}")
    private String secret;
    @Value("${tencent.wxmp.token}")
    private String token;
    @Value("${tencent.wxmp.aesKey}")
    private String aesKey;
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private int redisPort;
    @Value("${spring.redis.password}")
    private String redisPassword;
    // 默认指定存WxMP的信息到第5个库中
    private int redisDB = 5;

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    public WxMpService getWxMpService(){
        //WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        WxMpInRedisConfigStorage config = new WxMpInRedisConfigStorage();
        // 设置微信公众号的开发者ID(AppID)
        config.setAppId(appId);
        // 设置微信公众号的开发者密码(AppSecret)
        config.setSecret(secret);
        // 设置微信公众号的令牌(Token)
        config.setToken(token);
        // 设置微信公众号的消息加解密密钥(EncodingAESKey)
        config.setAesKey(aesKey);
        // 设置redis链接
        Jedis jedis = new Jedis(redisHost,redisPort);
        jedis.auth(redisPassword);
        jedis.select(redisDB);
        config.setJedis(jedis);
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(config);
        return wxMpService;
    }

    @Bean
    public SendMsgApi getSendMsgApi(){
        return new SendMsgApi();
    }

}
